<template>
  <el-row class="aside-content">
    <el-col :span="24" class="aside-col">
      <div class="aside-logo"></div>
      <el-menu
        class="aside-content-menu"
        router
        unique-opened
        @open="handleOpen"
        @close="handleClose"
        default-active="/orderform/allorder"
      >
        <el-sub-menu
          index="/use"
          v-if="activeuser.isadmin == 1 || activeuser.isadmin == 2"
        >
          <template #title>
            <el-icon><avatar /></el-icon>
            <span>系统管理</span>
          </template>
          <el-menu-item index="/use/list">用户列表</el-menu-item>
          <el-menu-item index="/use/rolelist">账号列表</el-menu-item>
        </el-sub-menu>
        <el-sub-menu index="/orderform">
          <template #title>
            <el-icon><shop /></el-icon>
            <span>订单管理</span>
          </template>
          <!-- <el-menu-item index="/orderform/addorder">手动添加订单</el-menu-item> -->
          <el-menu-item index="/orderform/matchingaddorder"
            >匹配添加订单</el-menu-item
          >
          <el-menu-item index="/orderform/allorder">查看订单</el-menu-item>
          <!-- <el-menu-item index="/orderform/belongorder" >查看所属订单</el-menu-item> -->
        </el-sub-menu>
        <el-menu-item index="/lutianmessage" class="lutian-view">
          <el-badge
            :value="allunreadnum"
            class="item"
            :show-zero="false"
            :offset="[10, 13]"
          >
            <el-icon><shop /></el-icon>
            <span>消息管理</span>
          </el-badge>
        </el-menu-item>
        <el-menu-item index="/lutianview" class="lutian-view">
          <el-icon><shop /></el-icon>
          <span>露天平台</span>
        </el-menu-item>
      </el-menu>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { ref, onMounted, inject } from "vue";
import { Avatar, Shop } from "@element-plus/icons-vue";

import { saveAllAccountlist } from "@/api/account/index.ts";
import { saveCookies } from "@/api/lutiancookie/index.ts";

import { ipc } from "@/utils/ipcRenderer";
import { ipcApiRoute } from "@/api/main.js";
import { ipcRenderer } from "electron";

// import { io } from "socket.io-client";

// const socket = io();
const activeuser = ref<any>({});
const allunreadnum = inject<any>("allunreadnum");
const logourl = "";
const handleOpen = (key: string, keyPath: string[]) => {
  // // console.log(key, keyPath);
  //
};
const handleClose = (key: string, keyPath: string[]) => {
  // // console.log(key, keyPath);
};

const accounts = inject<any>("accounts");
const filteraccounts = ref([]);
const accountsnum = ref(0);
const settimenum = ref(0);

const getActiveAccount = () => {
  if (activeuser.value.isadmin == 1 || activeuser.value.isadmin == 2) {
    let data = {
      keyword: "",
    };
    saveAllAccountlist(data).then((res) => {
      if (res.code == 200) {
        res.data.forEach((item) => {
          let foundIndex2 = accounts.value.findIndex(
            (item3) => item3.label == item.account && item3.value == item.id
          );
          if (foundIndex2 == -1) {
            let a = {
              value: item.id,
              label: item.account,
              cookie: "",
            };
            accounts.value.push(a);
          }
        });
        getAccountCookies();
      }
    });
  } else {
    if (activeuser.value.accounts != null && activeuser.value.accounts != "") {
      let accountsarr = activeuser.value.accounts.split(",");
      let accountsnamearr = activeuser.value.accountsname.split(",");

      for (let i = 0; i < accountsarr.length; i++) {
        let foundIndex2 = accounts.value.findIndex(
          (item3) =>
            item3.label == accountsnamearr[i] && item3.value == accountsarr[i]
        );
        if (foundIndex2 == -1) {
          let a = {
            value: accountsarr[i],
            label: accountsnamearr[i],
            cookie: "",
          };
          accounts.value.push(a);
        }
      }
      // // console.log(accounts.value);
      getAccountCookies();
    }
  }
};

const getAccountCookies = () => {
  let accountsvalue = accounts.value.map((obj) => obj.value);
  let data = {
    userId: activeuser.value.userId,
    accountids: JSON.stringify(accountsvalue),
  };
  saveCookies(data).then((res) => {
    if (res.code == 200) {
      res.data.forEach((item, index) => {
        accounts.value.forEach((item2, index2) => {
          if (item.accountid == item2.value && item2.stat == undefined) {
            let match = item.cookie.match(/bid_rid=(\d+)/);
            // 如果找到匹配的内容
            if (match) {
              // 第一个捕获组（即(\d+)）中的内容就是连续的数字
              let numbers = match[1];
              item2.cookie = item.cookie;
              item2.bid_rid = numbers;
              item2.unreadnum = 0;
            }
          }

          if (
            index + 1 == res.data.length &&
            index2 + 1 == accounts.value.length
          ) {
            let filteredArray = accounts.value.filter(
              (obj) => obj.cookie !== ""
            );
            filteraccounts.value = filteredArray;
            accountsnum.value = 0;

            if (filteraccounts.value.length < 150) {
              settimenum.value = 0;
            } else {
              let numbers = 50 / filteraccounts.value.length;
              let rounded = Math.round(numbers * 100) / 100;
              settimenum.value = rounded * 1000;
            }
            messageunread();
          }
        });
      });
    }
  });
};

const messageunread = () => {
  
  if (accountsnum.value < filteraccounts.value.length) {
    let accountsnum10 = accountsnum.value + 10;
    let data = filteraccounts.value.slice(accountsnum.value, accountsnum10);

    ipc
      .invoke(ipcApiRoute.getmessageunread, JSON.stringify(data))
      .then((res) => {

        if (res.length > 0) {
          res.forEach((item) => {
            if (item.data == null) {
              let obj = accounts.value.find((item2) => item2.label == item.id);
              if (obj) {
                obj.cookie = "";
                obj.unreadnum = 0;
                obj.stat = 0;
              }
            } else if (item.data != 'ECONNREFUSED') {
              let foundIndex2 = accounts.value.findIndex(
                (item3) => item3.label === item.id
              );
              if (foundIndex2 !== -1) {
                const foundItem = accounts.value[foundIndex2];
                if (item.data.unread_count != foundItem.unreadnum) {
                  accounts.value.splice(foundIndex2, 1); // 先移除该对象
                  foundItem.unreadnum = item.data.unread_count;
                  accounts.value.unshift(foundItem); // 再插入到数组的第一位
                }
              }
            }
            getallunreadnum();
          });
          setTimeout(() => {
            accountsnum.value = accountsnum10;
            messageunread();
          }, settimenum.value);
        }
      });
  } else {
    setTimeout(() => {
      accountsnum.value = 0;
      messageunread();
    }, 1000);

    //
    // messageunread();
  }
};

const getallunreadnum = () => {
  let num = 0;
  accounts.value.forEach((item, index) => {
    if (item.cookie != "") {
      num += item.unreadnum;
    }

    if (index + 1 == accounts.value.length) {
      allunreadnum.value = num;
    }
  });
};

onMounted(() => {
  accounts.value = [];
  filteraccounts.value = [];
  activeuser.value = JSON.parse(localStorage.getItem("currentUserstr"));
  setTimeout(() => {
    getActiveAccount();
  }, 2000);
});
</script>

<style scoped>
.aside-content {
  height: 100%;
  display: flex;
}
.aside-col {
  display: flex;
  flex-direction: column;
}
.aside-content-menu {
  /* height: 100%; */
  width: 100%;
  /* box-shadow: 0px 0px 12px rgba(0, 0, 0, .12); */
  border-right: 1px solid #dcdfe6;
  flex: 1;
  padding: 20px 0;
}
.aside-logo {
  background: #545c64;
}
</style>

<style>
.aside-logo img {
  height: 90px !important;
}
.menurouter {
  color: #fff;
  text-decoration: none;
}
.el-menu-item {
  padding: 0;
  display: flex;
  justify-content: center;
  font-size: 14px !important;
  font-weight: 500;
}
.lutian-view {
  padding-left: 0 !important;
}
.lutian-view span {
  font-size: 15px !important;
  font-weight: bold;
}
.el-sub-menu__title span {
  font-size: 15px !important;
  font-weight: bold;
}
</style>